﻿using AutoMapper.Internal.Mappers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;

namespace ERP.RBAC
{
    public class PermissionsService:IPermissionsService
    {

        private readonly IRepository<Permissions,int> _permissionRepo;

        public PermissionsService(IRepository<Permissions,int> permissionRepo)
        {
            _permissionRepo = permissionRepo;
        }

        public async Task<int> CreatePermission(Permissions permissions)
        {
           
            var i = await _permissionRepo.InsertAsync(permissions);

            return i == null ? 0 : 1;
        }

        public async Task<int> UpdatePermission(Permissions permissions)
        {
            // 添加参数验证
            if (permissions == null)
            {
                throw new ArgumentNullException(nameof(permissions), "权限对象不能为空");
            }

            if (permissions.Id <= 0)
            {
                throw new ArgumentException("无效的权限ID", nameof(permissions.Id));
            }

            // 记录请求数据
            Console.WriteLine($"更新权限开始处理: ID={permissions.Id}, Name={permissions.PermissionName}");

            // 检查实体是否存在
            bool exists = await _permissionRepo.AnyAsync(p => p.Id == permissions.Id);
            if (!exists)
            {
                Console.WriteLine($"找不到ID为{permissions.Id}的权限记录");
                throw new Exception($"找不到ID为{permissions.Id}的权限记录");
            }

            try
            {
                // 获取再更新
                var existingEntity = await _permissionRepo.GetAsync(permissions.Id);
                
                // 重要：只更新名称，保留Id不变
                existingEntity.PermissionName = permissions.PermissionName;
                
                // 保存更新
                var updatedEntity = await _permissionRepo.UpdateAsync(existingEntity);
                
                Console.WriteLine($"权限更新成功: ID={updatedEntity.Id}");
                return 1; // 成功返回1
            }
            catch (Exception ex)
            {
                // 记录错误
                Console.WriteLine($"更新权限失败: {ex.Message}");
                throw; // 重新抛出异常
            }
        }

        public async Task<List<Permissions>> GetPermission()
        {
            var permission = await _permissionRepo.GetListAsync();

            return permission;
        }

        public async Task<Permissions> GetPermissionById(int id)
        {
            var permission = await _permissionRepo.GetAsync(id);
            return permission;
        }

        public async Task DelPermission(int id)
        {
             await _permissionRepo.DeleteAsync(id);
        }

    }
}
